package com.bjqh.edu.UI.Activity.Index;

import android.content.res.Configuration;
import android.os.Bundle;
import android.os.Environment;
import android.support.design.widget.TabLayout;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.SurfaceView;
import android.view.View;
import android.view.ViewGroup;
import android.widget.FrameLayout;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.baijia.player.playback.LivePlaybackSDK;
import com.baijia.player.playback.PBRoom;
import com.baijia.player.playback.mocklive.OnPlayerListener;
import com.baijiahulian.common.networkv2.BJNetRequestManager;
import com.baijiahulian.common.networkv2.BJNetworkClient;
import com.baijiahulian.common.networkv2.HttpException;
import com.baijiahulian.livecore.context.LPConstants;
import com.baijiahulian.livecore.context.LPError;
import com.baijiahulian.livecore.context.LiveRoom;
import com.baijiahulian.livecore.context.OnLiveRoomListener;
import com.baijiahulian.livecore.launch.LPLaunchListener;
import com.baijiahulian.livecore.ppt.LPPPTFragment;
import com.baijiahulian.livecore.utils.LPErrorPrintSubscriber;
import com.baijiahulian.player.BJPlayerView;
import com.baijiahulian.player.bean.SectionItem;
import com.baijiahulian.player.bean.VideoItem;
import com.baijiahulian.player.playerview.BJBottomViewPresenter;
import com.baijiahulian.player.playerview.BJCenterViewPresenter;
import com.baijiahulian.player.playerview.BJTopViewPresenter;
import com.bjqh.edu.Base.AppConstants;
import com.bjqh.edu.Bean.Getoken;
import com.bjqh.edu.R;
import com.bjqh.edu.UI.Fragment.MessageListFragment;
import com.bjqh.edu.UI.Fragment.UserListFragment;
import com.google.gson.Gson;
import com.lzy.okgo.OkGo;
import com.lzy.okgo.cache.CacheMode;
import com.lzy.okgo.callback.StringCallback;

import java.io.File;

import butterknife.BindView;
import okhttp3.Call;
import okhttp3.Response;
import rx.android.schedulers.AndroidSchedulers;
import rx.functions.Action1;

public class VideoActivityNew extends AppCompatActivity implements LPLaunchListener {

    private PBRoom mRoom;

    private TextView mTextView, tvVideoStatus;
    private LPPPTFragment mPPTFragment;
    private BJPlayerView playerView;
    private TabLayout mTabLayout;
    private ViewPager mViewPager;

    private UserListFragment mUserListFragment;
    private MessageListFragment mMessageListFragment;
    private long rid;


    BJNetworkClient client = new BJNetworkClient.Builder()
            .setEnableLog(true)
            .build();
    final BJNetRequestManager netRequestManager = new BJNetRequestManager(client);

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.videoacitvitynew);
        mTextView = (TextView) findViewById(R.id.text1);
        playerView = (BJPlayerView) findViewById(R.id.playerView);
        mTabLayout = (TabLayout) findViewById(R.id.tabLayout);
        mViewPager = (ViewPager) findViewById(R.id.viewPager);
        tvVideoStatus = (TextView) findViewById(R.id.tv_video_status);
        ImageView ivBack = (ImageView) findViewById(R.id.iv_back);
        TextView tile = (TextView) findViewById(R.id.tv_title);
        tile.setText("视频回放");
        ivBack.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mRoom.quitRoom();
                finish();
            }
        });

        playerView.setTopPresenter(new BJTopViewPresenter(playerView.getTopView()));
        playerView.setCenterPresenter(new BJCenterViewPresenter(playerView.getCenterView()));
        playerView.setBottomPresenter(new BJBottomViewPresenter(playerView.getBottomView()));

        playerView.getTopViewPresenter().setOnBackClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                onBackPressed();
            }
        });


        rid = getIntent().getLongExtra("rid", 0);

        loadToken();


    }

    private void changeView() {
        ViewGroup vp1 = (ViewGroup) findViewById(R.id.small_container);
        ViewGroup vp2 = (ViewGroup) findViewById(R.id.big_container);
        View view1 = vp1.getChildAt(0);
        View view2 = vp2.getChildAt(0);

        mPPTFragment.onPause();

        vp1.removeView(view1);
        vp2.removeView(view2);

        vp1.addView(view2);
        vp2.addView(view1);

        mPPTFragment.onResume();

        View surface;
        if (view2 instanceof BJPlayerView) {
            surface = ((BJPlayerView) view2).getVideoView().getChildAt(0);
            ((SurfaceView) surface).setZOrderMediaOverlay(true);
            ((SurfaceView) ((FrameLayout) ((RelativeLayout) view1).getChildAt(0)).getChildAt(0)).setZOrderMediaOverlay(false);
        } else {
            surface = ((BJPlayerView) view1).getVideoView().getChildAt(0);
            ((SurfaceView) ((FrameLayout) ((RelativeLayout) view2).getChildAt(0)).getChildAt(0)).setZOrderMediaOverlay(true);
            ((SurfaceView) surface).setZOrderMediaOverlay(false);
        }
    }

    @Override
    public void onConfigurationChanged(Configuration newConfig) {
        super.onConfigurationChanged(newConfig);
        if (playerView != null) {
            playerView.onConfigurationChanged(newConfig);
        }
    }

    @Override
    public void onBackPressed() {
        if (!playerView.onBackPressed()) {
            super.onBackPressed();
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        if (playerView != null) {
            playerView.onResume();
        }
    }

    @Override
    protected void onPause() {
        super.onPause();
        if (playerView != null) {
            playerView.onPause();
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (playerView != null) {
            playerView.onDestroy();
        }
        if (null != mRoom) {
            mRoom.quitRoom();
        }

    }

    @Override
    public void onLaunchSteps(final int step, final int totalStep) {
        mTextView.setText("enter Room " + (step * 100 / totalStep) + "%");
        Log.e("Enter", "enter Room " + (step * 100 / totalStep) + "% at:" + System.currentTimeMillis());
    }

    @Override
    public void onLaunchError(LPError error) {
        Toast.makeText(this, "进房间失败" + error.getCode() + " " + error.getMessage(), Toast.LENGTH_SHORT).show();
    }

    @Override
    public void onLaunchSuccess(LiveRoom liveRoom) {
        Log.e("Enter", "enter Room Success at:" + System.currentTimeMillis());
        mRoom.getObservableOfUserNumberChange()
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Action1<Integer>() {
                    @Override
                    public void call(Integer integer) {
                        mTextView.setVisibility(View.GONE);
                        mTextView.setText("当前用户数: " + integer);
                    }
                });
        playerView.playVideo();

    }

    private PagerAdapter pagerAdapter = new FragmentPagerAdapter(getSupportFragmentManager()) {
        @Override
        public Fragment getItem(int position) {
            return mMessageListFragment;
     /*       if (position == 0) {
                return mMessageListFragment;
            }

            else if (position == 1) {
                return mUserListFragment;
            } else {
                return mMessageListFragment;
            }*/
        }

        @Override
        public CharSequence getPageTitle(int position) {
            if (position == 0) {
                return "聊天";
            } else if (position == 1) {
                return "用户名单";
            } else {
                return "聊天";
            }
        }

        @Override
        public int getCount() {
            return 1;
        }
    };


    public void loadToken() {
        OkGo.post(AppConstants.BASE_URL + "/rtu/getPayToken.shtml")
                .tag(this)
                .cacheKey("cacheKey")
                .cacheMode(CacheMode.DEFAULT)
                .params("id", rid)
                .execute(new StringCallback() {
                    @Override
                    public void onSuccess(String s, Call call, Response response) {
                        Log.i("房间token", s);
                        Gson gson = new Gson();
                        Getoken getoken = gson.fromJson(s, Getoken.class);
                        if (getoken.getMsg().equals("success")) {

                            mTabLayout.addTab(mTabLayout.newTab().setText("聊天"));
//                            mTabLayout.addTab(mTabLayout.newTab().setText("用户名单"));
//                            mTabLayout.addTab(mTabLayout.newTab().setText("聊天"));

                            String token = getoken.getToken();
                            mRoom = LivePlaybackSDK.newPlayBackRoom(VideoActivityNew.this, rid, token, LPConstants.LPDeployType.Product);
//                            mUserListFragment = new UserListFragment();
//                            mUserListFragment.setRoom(mRoom);
                            mMessageListFragment = new MessageListFragment();
                            mMessageListFragment.setRoom(mRoom);
                            mRoom.getObservableOfVideoStatus().observeOn(AndroidSchedulers.mainThread())
                                    .subscribe(new LPErrorPrintSubscriber<Boolean>() {
                                        @Override
                                        public void call(Boolean aBoolean) {
                                            tvVideoStatus.setText(aBoolean ? "视频开启" : "视频关闭");
                                            tvVideoStatus.setVisibility(View.GONE);
                                            System.out.println("hola video status: " + aBoolean);

                                        }
                                    });

                            mPPTFragment = new LPPPTFragment();
                            mPPTFragment.setLiveRoom(mRoom);
                            mPPTFragment.setFlingEnable(true);
                            mPPTFragment.setAnimPPTEnable(false);
                            getSupportFragmentManager().beginTransaction().add(R.id.small_container, mPPTFragment).commit();
                            getSupportFragmentManager().executePendingTransactions();
                            mRoom.setOnLiveRoomListener(new OnLiveRoomListener() {
                                @Override
                                public void onError(LPError lpError) {
                                    Log.e("OnLiveRoomListener", "code" + lpError.getCode() + " msg:" + lpError.getMessage());
                                }
                            });
                            mRoom.enterRoom(VideoActivityNew.this);


                            mRoom.bindPlayerView(playerView);
                            mViewPager.setAdapter(pagerAdapter);
                            mTabLayout.setupWithViewPager(mViewPager);
                            mRoom.setOnPlayerListener(new OnPlayerListener() {

                                @Override
                                public void onVideoInfoInitialized(BJPlayerView playerView, long duration, HttpException exception) {
                                    Log.e("duration", String.valueOf(duration));
                                    Toast.makeText(VideoActivityNew.this, "" + duration, Toast.LENGTH_SHORT).show();
                                }

                                @Override
                                public void onError(BJPlayerView playerView, int code) {
                                    Log.e("onError", String.valueOf(code));
                                }

                                @Override
                                public void onUpdatePosition(BJPlayerView playerView, int position) {
                                    Log.e("onUpdatePosition", String.valueOf(position));
                                }

                                @Override
                                public void onSeekComplete(BJPlayerView playerView, int position) {
                                    Log.e("onSeekComplete", String.valueOf(position));
                                    if (!playerView.isPlaying()) playerView.playVideo(position);
                                }

                                @Override
                                public void onSpeedUp(BJPlayerView playerView, float speedUp) {

                                }

                                @Override
                                public void onVideoDefinition(BJPlayerView playerView, int definition) {
                                }

                                @Override
                                public void onPlayCompleted(BJPlayerView playerView, VideoItem item, SectionItem nextSection) {
                                }

                                @Override
                                public void onVideoPrepared(BJPlayerView playerView) {
                                    ((SurfaceView) playerView.getVideoView().getChildAt(0)).setZOrderMediaOverlay(true);
                                    ((SurfaceView) ((FrameLayout) ((RelativeLayout) mPPTFragment.getView()).getChildAt(0)).getChildAt(0)).setZOrderMediaOverlay(false);
                                }
                            });


                        } else {
                            Toast.makeText(VideoActivityNew.this, "小主，该课程暂时没有视频哦~~", Toast.LENGTH_SHORT).show();
                            finish();
                        }


                    }

                    @Override
                    public void onError(Call call, Response response, Exception e) {
                        super.onError(call, response, e);
                        Toast.makeText(VideoActivityNew.this, "报告小主，服务器被外星人偷走啦~~", Toast.LENGTH_SHORT).show();
                    }
                });

    }


}
